package org.peterf.foxish.component.updater;

import org.peterf.foxish.component.property.Updatable;
import org.peterf.foxish.component.updater.interfaces.GradualReversable;
import org.peterf.foxish.component.updater.interfaces.Updater;

public class LinearLoopUpdater implements Updater {

    private int loop;

    private int loopDone = 0;

    private float period;

    private GradualReversable updater;

    public LinearLoopUpdater(GradualReversable updater, float period, int loop) {
        this.updater = updater;
        this.period = period;
        this.loop = loop;
    }

    public boolean isFinished() {
        return loop >= 0 && loopDone >= loop;
    }

    public void reset() {
        loopDone = 0;
    }

    public void update(Updatable updatable, float elapsed) {
        while (updater.isFinished()) {
            if (loop < 0) {
                updater.reverse();
                break;
            } else if (++loopDone < loop) {
                updater.reverse();
            } else {
                return;
            }
        }
        updater.setProgress(updater.getProgress() + elapsed / period);
        updater.update(updatable, elapsed);
    }

}
